<!-- uncomment for open list.html slone -->
<!-- script type="text/javascript" src="/jquery-1.11.1.min.js"></script -->

<style>
#body {
	/*background: #f8f8f8;*/
    font-family: 'PT Sans', Helvetica, Arial, sans-serif;
    text-align: center;
    color: #fff;
    /*overflow: hidden;
    width: 1000px;
    margin: 100px auto 0 auto;
    padding-bottom: 60px;*/
}

.table {
    float: left;
    width: 140px;
    margin: 20px 14px 0 14px;
    background: #f8f8f8;
    -moz-border-radius: 6px;
    -webkit-border-radius: 6px;
    border-radius: 6px;
    -moz-box-shadow: 0 2px 15px 0 rgba(0,0,0,.2);
    -webkit-box-shadow: 0 2px 15px 0 rgba(0,0,0,.2);
    box-shadow: 0 2px 15px 0 rgba(0,0,0,.2);
    
}

.table strong { font-weight: 700; color: #3d3d3d; }

.table-header {
    padding: 10px 0;
    background: #3d3d3d;
    -moz-border-radius-topleft: 6px;
    -moz-border-radius-topright: 6px;
    -webkit-border-top-left-radius: 6px;
    -webkit-border-top-right-radius: 6px;
    border-top-left-radius: 6px;
    border-top-right-radius: 6px;
    background-image: -webkit-gradient(linear, left top, left bottom, from(#494949), to(#3e3e3e));
    background-image: -webkit-linear-gradient(top, #494949, #3e3e3e);
    background-image: -moz-linear-gradient(top, #494949, #3e3e3e);
    background-image: -o-linear-gradient(top, #494949, #3e3e3e);
    background-image: -ms-linear-gradient(top, #494949, #3e3e3e);
    background-image: linear-gradient(to bottom, #494949, #3e3e3e);
}

.table-header h2 { font-size: 30px; font-weight: 700; text-shadow: 0 -2px 0 rgba(0,0,0,.25); }
.table-header h3 { margin: 0; font-size: 20px; font-weight: 400; text-shadow: 0 -2px 0 rgba(0,0,0,.25); }

.table-space { height: 10px; }

.table-text {
    margin: 15px 30px 0 30px;
    padding: 0 10px 15px 10px;
    border-bottom: 1px solid #ddd;
    text-align: left;
    line-height: 30px;
    font-size: 16px;
    color: #888;
}

.table-features {
    margin: 15px 30px 0 30px;
    /*padding: 0 10px 15px 10px;*/
    border-bottom: 1px solid #ddd;
    text-align: center;
    line-height: 30px;
    font-size: 16px;
    color: #888;
}

.table-features img {
	width: 60px;
	
}
.table_desc {
    margin-top: 15px;
    height: 36px;
    padding-bottom: 20px;
    color: #3d3d3d;
    font-size: 14px;
}

</style>
	<script src="/socket.io/socket.io.js"></script>
	<script>
		var gSocketIo = io.connect();
		var gLayout = {};

		$(function() {

			gSocketIo.on('layout', function (str) {
				if (('$' != str.charAt(0)) || ('$' != str.charAt(str.length - 1))) {
					alert('packet error :', str);
					return false;
				}
				//console.log(str);

				var curIdx = 1, findIdx;

				findIdx = str.indexOf(':', curIdx);
				//cmdPacket = str.substr(curIdx, findIdx-curIdx);
				curIdx = findIdx + 1;

				findIdx = str.indexOf(',', curIdx);
				gLayout.cx = Number(str.substr(curIdx, findIdx-curIdx));
				curIdx = findIdx + 1;

				findIdx = str.indexOf(',', curIdx);
				gLayout.cy = Number(str.substr(curIdx, findIdx-curIdx));
				curIdx = findIdx + 1;

				findIdx = str.indexOf(',', curIdx);
				gLayout.row = Number(str.substr(curIdx, findIdx-curIdx));
				curIdx = findIdx + 1;

				findIdx = str.indexOf(',', curIdx);
				gLayout.column = Number(str.substr(curIdx, findIdx-curIdx));
				curIdx = findIdx + 1;

				gLayout.Buttons = new Array();
				var btnIdx = 0;
				while (true) {
					findIdx = str.indexOf('[', curIdx);
					if (0 > findIdx) {
						break;
					}
					curIdx = findIdx + 1;

					var button = {};

					findIdx = str.indexOf(',', curIdx);
					button.cid = Number(str.substr(curIdx, findIdx-curIdx));
					curIdx = findIdx + 1;

					findIdx = str.indexOf(',', curIdx);
					button.bid = Number(str.substr(curIdx, findIdx-curIdx));
					curIdx = findIdx + 1;

					findIdx = str.indexOf(',', curIdx);
					button.rid = Number(str.substr(curIdx, findIdx-curIdx));
					curIdx = findIdx + 1;

					findIdx = str.indexOf(',', curIdx);
					button.name = str.substr(curIdx, findIdx-curIdx);
					curIdx = findIdx + 1;

					findIdx = str.indexOf(',', curIdx);
					button.notUsed = Number(str.substr(curIdx, findIdx-curIdx));
					curIdx = findIdx + 1;

					findIdx = str.indexOf(',', curIdx);
					button.pos = Number(str.substr(curIdx, findIdx-curIdx));
					curIdx = findIdx + 1;

					findIdx = str.indexOf(',', curIdx);
					button.x = Number(str.substr(curIdx, findIdx-curIdx));
					curIdx = findIdx + 1;

					findIdx = str.indexOf(',', curIdx);
					button.y = Number(str.substr(curIdx, findIdx-curIdx));
					curIdx = findIdx + 1;

					findIdx = str.indexOf(',', curIdx);
					button.cx = Number(str.substr(curIdx, findIdx-curIdx));
					curIdx = findIdx + 1;

					findIdx = str.indexOf(',', curIdx);
					button.cy = Number(str.substr(curIdx, findIdx-curIdx));
					curIdx = findIdx + 1;

					findIdx = str.indexOf(',', curIdx);
					button.rtype = Number(str.substr(curIdx, findIdx-curIdx));
					if (button.rtype) {
						button.flagRemote = parseInt(button.rtype / 100);
						button.isHeating = parseInt(button.rtype / 10) % 10;
					}
					curIdx = findIdx + 1;

					findIdx = str.indexOf(',', curIdx);
					button.status = Number(str.substr(curIdx, findIdx-curIdx));
					curIdx = findIdx + 1;

					findIdx = str.indexOf(',', curIdx);
					button.stime = Number(str.substr(curIdx, findIdx-curIdx));
					curIdx = findIdx + 1;

					findIdx = str.indexOf(',', curIdx);
					button.etime = Number(str.substr(curIdx, findIdx-curIdx));
					curIdx = findIdx + 1;

					//console.log(button);
					gLayout.Buttons.push(button);
				}

				if (gLayout.Buttons.length) {
					initLayout(gLayout);
				} else {
					//document.body.innerHTML = str;
					$('body').empty();
					$('<div />').attr('align', 'center').appendTo('body');
					$('div').append(function (index) {
						return '<h1>장비 연결을 확인하세요<h1>';
					});
				}

				var url = document.URL;
				findIdx = url.lastIndexOf('?id=');
				if (-1 < findIdx) {
					gSocketIo.emit('layout', str + url.substr(findIdx + 4));
				} else {
					gSocketIo.emit('layout', str);
				}
			});
			
			gSocketIo.on('nodevice', function (str) {
				$('body').empty();
				$('<div />').attr('align', 'center').appendTo('body');
				$('div').append(function (index) {
					return '<h1>장비 연결을 확인하세요<h1>';
				});

				gSocketIo.emit('nodevice', str);
			});

			gSocketIo.on('update', function (str) {
				if (('$' != str.charAt(0)) || ('$' != str.charAt(str.length - 1))) {
					alert('packet error :', str);
					return false;
				}
				//console.log(str);

				var curIdx = 1, findIdx;

				findIdx = str.indexOf(':', curIdx);
				//cmdPacket = str.substr(curIdx, findIdx-curIdx);
				curIdx = findIdx + 1;
				
				while (true) {
					findIdx = str.indexOf('[', curIdx);
					if (0 > findIdx) {
						break;
					}
					curIdx = findIdx + 1;

					var cid, bid, rid, status, stime, etime;

					findIdx = str.indexOf(',', curIdx);
					cid = Number(str.substr(curIdx, findIdx-curIdx));
					curIdx = findIdx + 1;

					findIdx = str.indexOf(',', curIdx);
					bid = Number(str.substr(curIdx, findIdx-curIdx));
					curIdx = findIdx + 1;

					findIdx = str.indexOf(',', curIdx);
					rid = Number(str.substr(curIdx, findIdx-curIdx));
					curIdx = findIdx + 1;

					findIdx = str.indexOf(',', curIdx);
					status = Number(str.substr(curIdx, findIdx-curIdx));
					curIdx = findIdx + 1;

					findIdx = str.indexOf(',', curIdx);
					stime = Number(str.substr(curIdx, findIdx-curIdx));
					curIdx = findIdx + 1;

					findIdx = str.indexOf(',', curIdx);
					etime = Number(str.substr(curIdx, findIdx-curIdx));
					curIdx = findIdx + 1;

					var imgSrc = findImg(status);
					if (imgSrc.length) {
						for (var i=0; i<gLayout.Buttons.length; i++) {
							if ((gLayout.Buttons[i].cid == cid)
								&& (gLayout.Buttons[i].bid == bid)
								&& (gLayout.Buttons[i].rid == rid)) {
								gLayout.Buttons[i].status = status;
								gLayout.Buttons[i].stime = stime;
								gLayout.Buttons[i].etime = etime;
								if ((0x01 == status) && gLayout.Buttons[i].rtype) {
									imgSrc = 'img/status_ready.png';
								}
								$('img').eq(gLayout.Buttons[i].pos).attr('src', imgSrc);

								if(0!=stime){
									var d = new Date();
									d.setTime(stime*1000);
									$('div.stime').eq(gLayout.Buttons[i].pos).text(d.getMonth()+1+'월'+d.getDate()+'일 '+d.getHours()+':'+d.getMinutes());
									$('div.etime').eq(gLayout.Buttons[i].pos).text(formatTime2(etime));
								}else{
									$('div.stime').eq(gLayout.Buttons[i].pos).text("");
									$('div.etime').eq(gLayout.Buttons[i].pos).text("");
								}
								break;
							}
						}
					}
				}

				gSocketIo.emit('update', str);
			});

			gSocketIo.on('temperature', function (str) {
				if (('$' != str.charAt(0)) || ('$' != str.charAt(str.length - 1))) {
					alert('packet error :', str);
					return false;
				}
				//console.log(str);

				var curIdx = 1, findIdx;
				var curValue, setValue;

				findIdx = str.indexOf(':', curIdx);
				//cmdPacket = str.substr(curIdx, findIdx-curIdx);
				curIdx = findIdx + 1;

				findIdx = str.indexOf(',', curIdx);
				curValue = Number(str.substr(curIdx, findIdx-curIdx));
				curIdx = findIdx + 1;

				findIdx = str.indexOf(',', curIdx);
				setValue = Number(str.substr(curIdx, findIdx-curIdx));
				curIdx = findIdx + 1;

				var nowDate = new Date();
				var str = "Temperature updated : " + nowDate.toLocaleString();
				$("#div-1").text(str);
				str = "PV : " + curValue/10 + ", SV : " + setValue/10;
				$("#div-2").text(str);

				gSocketIo.emit('temperature', str);
			});
		});
		
		function initLayout(layout) {
			//console.log(layout);

			$('#body').empty();

			var html = '';
			// <div id="body">
			html += '<div id="body">';
			//html += '<table>';

			for (var r=0; r<layout.row; r++) {
				//html += '<tr>';
				for (var c=0; c<layout.column; c++) {
					var idx = r*layout.column + c;

				    // <div class="table">
    				html += '<div class="table">';

					if (layout.Buttons.length > idx) {
                        var field_rname='',field_img='', field_stime='', field_etime='' ;
						if (layout.Buttons[idx].pos == idx) {
						    field_rname = layout.Buttons[idx].name ;
    						var imgSrc = findImg(layout.Buttons[idx].status, layout.Buttons[idx].rtype);
						    field_img = '<img src="'+imgSrc+'" pos="' + idx+'" >' ;

                            var st='', et='' ;
							if(layout.Buttons[idx].stime != 0){
								var d = new Date();
								d.setTime(layout.Buttons[idx].stime*1000);
								field_stime = d.getMonth()+1+'??+d.getDate()+'월'+d.getHours()+'일'+d.getMinutes();
								field_etime = formatTime2(layout.Buttons[idx].etime);
							} 
						}

					    // relay name <div class="table-header"><h3>Relay_10_2</h3></div>
        				html += '<div class="table-header"><h3>'+field_rname+'</h3></div>';

        				// icon <div class="table-features"><img src="img/status_on.png"></div>
    				    html += '<div class="table-features">'+field_img+'</div>';

                        // time <div class="table_desc"><div class="stime">4월1일 18:34</div><div class="etime">02시간05분</div></div>
    				    html += '<div class="table_desc"><div class="stime">'+field_stime+'</div><div class="etime">'+field_etime+'</div></div>';

					}
				    // </div>
    				html += '</div>';
				}
				//html += '</tr>';
			}
			
			//html += '</table>';
			// </div>
			html += '</div>';

			//document.body.innerHTML = html;
			$('#body').html(html);

			$('#body img').click(function () {
				var curIdx = 0, findIdx;

				var pos = $(this).attr('pos');
				var status = -1;
				switch (gLayout.Buttons[pos].status) {
				case 0x00:	// OFF
					status = 0x01;	// ON
					break;
				case 0x01:	// ON
					$('div.stime').eq(gLayout.Buttons[pos].pos).text("");
					$('div.etime').eq(gLayout.Buttons[pos].pos).text("");
					if (gLayout.Buttons[pos].rtype) {
						status = gLayout.Buttons[pos].isHeating ? 0x04 : 0x03;	// HEATING, COOLING
					} else {
						status = 0x00;	// OFF
					}
					break;
				case 0x02:	// AIR
					if (gLayout.Buttons[pos].rtype) {
						status = 0x00;	// OFF
					}
					break;
				case 0x03:	// COOLING
				case 0x04:	// HEATING
					if (gLayout.Buttons[pos].rtype) {
						if (gLayout.Buttons[pos].flagRemote) {
							// off - on - cooling/heating - off
							status = 0x00;	// OFF
						} else {
							// off - on - cooling/heating - air - off
							status = 0x02;	// AIR
						}
					}
					break;
				case 0x20:	// PENDING
					alert('처리중입니다...');
					break;
				case 0x40:	// UNKNOWN
					alert('장비오류 확인바랍니다!!!');
					status = 0x40;	// UNKNOWN // for getStatus
					break;
				}
				if (-1 < status) {
					var cid = gLayout.Buttons[pos].cid;
					var bid = gLayout.Buttons[pos].bid;
					var rid = gLayout.Buttons[pos].rid;
					var setPkt = '$set:[' + cid + ',' + bid + ',' + rid + ',' + status + ',],$';
					console.log('setPkt:' + setPkt);

					gSocketIo.emit('set', setPkt);
				}
			});
		}
		
		function findImg(status, rtype) {
			var imgSrc = '';
			switch (status) {
			case 0x00:	// OFF
				imgSrc = 'img/status_off.png';
				break;
			case 0x01:	// ON
				imgSrc = rtype ? 'img/status_ready.png' : 'img/status_on.png';
				break;
			case 0x02:	// AIR
				imgSrc = 'img/status_air.png';
				break;
			case 0x03:	// COOLING
				imgSrc = 'img/status_cooling.png';
				break;
			case 0x04:	// HEATING
				imgSrc = 'img/status_heating.png';
				break;
			case 0x20:	// PENDING
				imgSrc = 'img/status_pending.png';
				break;
			case 0x40:	// UNKNOWN
				imgSrc = 'img/status_unknown.png';
				break;
			default:
				imgSrc = 'img/status_blank.png';
				break;
			}
			return imgSrc;
		}
		
		function formatTime(minutes) {
			var hour = parseInt(minutes / 60);
			var min = minutes % 60;
			
			var format = hour;
			format += ':';
			if (10 > min) {
				format += '0';
			}
			format += min;
			console.log(hour + ',' + min + ',' + format);

			return format;
		}

		function formatTime2(seconds) {
			var hour = Math.floor(seconds/3600);
			var min = Math.floor((seconds - hour*3600)/60);
                        var sec = Math.floor(seconds - hour * 3600 - min * 60);
			
			var format;
			if (10 > hour) {
				format = '0';
				format += hour;
			}else{
				format = hour;
			}
			format += '시간';
			if (10 > min) {
				format += '0';
			}
			format += min;
			format += '분';
			//if (10 > sec) {
			//	format += '0';
			//}
			//format += sec;

			return format;
		}
	</script>
	<div id="body"></div>
